from PyQt6.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
from 本体 import Ui_MainWindow  # 从生成的Python文件中导入界面
from Process_application import Process_application
import ncmdump  # 导入处理模块


# 多进程工作函数，必须在全局作用域中定义
def process_worker(files, output):
    for name in files:
        ncmdump.dump(name, output)


class MyWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        self.process_app = Process_application()
        super().__init__()
        self.setupUi(self)
        self.choice = 2

        # 连接按钮点击事件
        self.pushButton.clicked.connect(self.select_file_ncm)  # 选择ncm格式的文件
        self.pushButton_2.clicked.connect(self.select_output_file)  # 选择输出目录
        self.pushButton_3.clicked.connect(self.get_run)  # 运行
        self.checkBox.clicked.connect(self.select_2_process)
        self.checkBox_2.clicked.connect(self.select_4_process)
        self.selected_files = []  # 用于存储选中的文件
        self.selected_output_files = ''  # 用于存储输出目录

    # 选择ncm文件的槽函数
    def select_file_ncm(self):
        files, _ = QFileDialog.getOpenFileNames(self, "选择文件", "", "NCM Files (*.ncm);;All Files (*)")
        if files:
            self.selected_files = files
            self.textEdit.setText("\n".join(files))  # 显示选中的文件路径

    # 选择输出目录的槽函数
    def select_output_file(self):
        self.selected_output_files = QFileDialog.getExistingDirectory(self, "选择文件夹")
        if self.selected_output_files:  # 如果用户选择了文件夹
            print(f"选择的文件夹路径是: {self.selected_output_files}")
            self.lineEdit.setText(self.selected_output_files)  # 显示输出目录

    # 选择进程
    def select_2_process(self):
        process_app = self.process_app
        process_app.choice_process(2)
        self.choice = 2

    def select_4_process(self):
        choice = self.choice
        process_app = self.process_app
        process_app.choice_process(4)
        self.choice = 4

    # 运行
    def get_run(self):
        choice = self.choice
        files = self.selected_files
        output = self.selected_output_files
        process_app = self.process_app
        processes = []  # 用于存储进程
        # 判断文件数是否小于进程数
        if len(files) < choice:
            choice = 2
        if choice == 4:
            processes = process_app.four_process(process_worker, files, output)
        else:
            processes = process_app.double_process(process_worker, files, output)
        for p in processes:
            p.start()
        for p in processes:
            p.join()
        QMessageBox.information(self, "完成", "所有文件已处理完毕。")










